'use strict';

const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  console.log('获取聊天消息云函数被调用，参数:', event)
  
  const { taskId, userId, messageType, page = 1, pageSize = 20, isAdmin = false } = event
  
  // 权限验证
  let uid
  if (!isAdmin) {
    const uniIdIns = uniID.createInstance({
      context: context
    })
    
    const checkTokenRes = await uniIdIns.checkToken(event.uniIdToken)
    if (checkTokenRes.code !== 0) {
      return { code: 401, msg: 'token无效或已过期' }
    }
    uid = checkTokenRes.uid
    
    // 非管理员只能查看自己相关的消息
    if (userId && userId !== uid) {
      return { code: 403, msg: '无权查看其他用户的消息' }
    }
  } else {
    console.log('管理员访问，跳过token验证')
    uid = 'admin'
  }

  const db = uniCloud.database()
  const collection = db.collection('chatMessages')
  
  try {
    // 构建查询条件
    let whereCondition = {}
    
    // 按任务ID筛选
    if (taskId) {
      whereCondition.taskId = taskId
    }
    
    // 按用户ID筛选（发送者或接收者）
    if (userId) {
      whereCondition = db.command.or([
        { senderId: userId },
        { receiverId: userId }
      ])
    } else if (!isAdmin && uid !== 'admin') {
      // 非管理员只能看自己相关的消息
      whereCondition = db.command.or([
        { senderId: uid },
        { receiverId: uid }
      ])
    }
    
    // 按消息类型筛选
    if (messageType) {
      if (whereCondition.taskId || whereCondition.senderId || whereCondition.receiverId) {
        whereCondition = db.command.and([
          whereCondition,
          { type: messageType }
        ])
      } else {
        whereCondition.type = messageType
      }
    }
    
    console.log('查询条件:', JSON.stringify(whereCondition))
    
    // 查询总数
    const countResult = await collection.where(whereCondition).count()
    const total = countResult.total
    
    // 分页查询消息
    const skip = (page - 1) * pageSize
    const messagesResult = await collection
      .where(whereCondition)
      .orderBy('createTime', 'desc') // 按创建时间倒序
      .skip(skip)
      .limit(pageSize)
      .get()
    
    const messages = messagesResult.data || []
    
    console.log(`查询到 ${messages.length} 条消息，总计 ${total} 条`)
    
    // 计算分页信息
    const totalPages = Math.ceil(total / pageSize)
    
    return {
      code: 200,
      msg: '查询成功',
      data: {
        messages: messages,
        pagination: {
          page: page,
          pageSize: pageSize,
          total: total,
          totalPages: totalPages,
          hasMore: page < totalPages
        }
      }
    }
    
  } catch (error) {
    console.error('查询聊天消息失败:', error)
    return {
      code: 500,
      msg: '查询失败: ' + error.message,
      data: {
        messages: [],
        pagination: {
          page: 1,
          pageSize: pageSize,
          total: 0,
          totalPages: 0,
          hasMore: false
        }
      }
    }
  }
}